package cn.tom.tools;

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.mail.javamail.ConfigurableMimeFileTypeMap;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class Base64ImageUtils {



    /**
     * 将图片内容编码为字符串
     * @param bytes
     * @return
     *
     *  图片的字节流 转为 字符流
     * */
    public static String encodeImageToBase64(byte[] bytes){
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(bytes).trim();
    }

    /**
     * 将图片内容解码为输入流
     * @param base
     * @return
     * 将 字符流 转为字节流
     * */
    public static InputStream decodeBase64ToImage(String base){
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] decodeBytes = null;
        try{
            decodeBytes = decoder.decodeBuffer(base);
        }catch (IOException e){
            e.printStackTrace();
        }
        return new ByteArrayInputStream(decodeBytes);
    }


    /**
     *   将图片输入流转换为输入流资源
     * @Param content
     * @return
     * */
    public static InputStreamResource body(String content){
        return new InputStreamResource(Base64ImageUtils.decodeBase64ToImage(content));
    }

    /**
     * 设置响应的头部信息
     * @param size
     * @param name
     * @return
     * */
    public static HttpHeaders httpHeaders(String size, String name){
        final HttpHeaders httpHeaders = new HttpHeaders();
        ConfigurableMimeFileTypeMap configurableMimeFileTypeMap = new ConfigurableMimeFileTypeMap();
        httpHeaders.setContentType(MediaType.valueOf(configurableMimeFileTypeMap.getContentType(name)));
        httpHeaders.set(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename*=UTF-8''" + encode(name));
        httpHeaders.set(HttpHeaders.CONTENT_LENGTH,size);
        return httpHeaders;
    }

    /**
     * 文件名进行编码
     * @param name
     * @return
     * */
    public static String encode(String name){
        try{
            return URLEncoder.encode(name, StandardCharsets.UTF_8.name());
        }catch (UnsupportedEncodingException e){
            throw new RuntimeException(e.getMessage());
        }
    }
}
